package com.code2roc.fastboot.framework.redis;

import com.code2roc.fastboot.framework.extra.enums.GlobalEnum;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;


    @Bean(destroyMethod = "shutdown") // 服务停止后调用 shutdown 方法。
    public RedissonClient redisson() throws IOException {
        // 1.创建配置
        Config config = new Config();
        // 集群模式
        // config.useClusterServers().addNodeAddress("127.0.0.1:7004", "127.0.0.1:7001");
        // 2.根据 Config 创建出 RedissonClient 示例。
        SingleServerConfig singleServerConfig = config.useSingleServer();
        String serverUrl = "redis://" + host + ":" + port;
        singleServerConfig.setAddress(serverUrl);
        if(!StringUtil.isEmpty(password)){
            singleServerConfig.setPassword(password);
        }
        singleServerConfig.setDatabase(GlobalEnum.RedisDBNum.CheckLock.get_value());
        return Redisson.create(config);
    }

}
